<?php
defined('ENV') || exit('illegal Access! @110');
/**
 * desc 获取请求参数, 只检查数据的合法性, 并不改变数据内容
 * Class Request
 */
class Request
{
    public static $data = false;
    public $isValid = false;

    public static function Post($key, $default=NULL)
    {
        self::$data = isset($_POST[$key]) ? $_POST[$key] : $default;
        self::valid($key);

        return self::$data;
    }
    
    public static function Get($key, $default=NULL)
    {
        self::$data = isset($_GET[$key]) ? $_GET[$key] : $default;
        self::valid($key);

        return self::$data;
    }

    public static function Cookie($key, $default=NULL)
    {
        self::$data = isset($_COOKIE[$key]) ? $_COOKIE[$key] : $default;
        self::valid($key);

        return self::$data;
    }

    public static function Route($key, $default=NULL)
    {
        self::$data = isset(Route::$args[$key]) ? Route::$args[$key] : $default;
        self::valid($key);

        return self::$data;
    }
    
    public static function Server($key, $default=NULL)
    {
        self::$data = isset($_SERVER[$key]) ? $_SERVER[$key] : $default;
        return self::$data;
    }
    
    public static function Session($key, $default=NULL)
    {
        self::$data = isset($_SESSION[$key]) ? $_SESSION[$key] : $default;
        return self::$data;
    }

    /**
     * desc 检测数据的合法性
     * @param string $key 参数键
     * @param string $value 参数值
     * @throws Exception
     */
    public static function valid($key, $value='')
    {
        $value = !empty($value) ? $value : self::$data;
        
        if (!is_null($value)) {
            if (!is_array($value)) {
                $value = array($value);
            }
            
            try {
                foreach ($value as $v) {
                    $verifyRule = implode(':', array(MODULE_NAME, CONTROLLER_NAME, ACTION_NAME));
                    Verify::check($key, $v, $verifyRule);
                }
            } catch (Exception $e) {
                Response::error($e->getMessage());
            }
        }
    }
    
    public static function isPost()
    {
        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    
    /**
     * 获取当前访问的URL
     */
    public static function Url()
    {
        return $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    }

    /**
     * 一般获得用户IP都是使用$_SERVER['REMOTE_ADDR']这个环境变量，但是此变量只会纪录最后一个主机IP，所以当用户浏览器有设定Proxy时，就无法取得他的真实IP。
     * 这时可以使用另一个环境变量$_SERVER['HTTP_X_FORWARDED_FOR']，它会纪录所经过的主机IP，但是只有在用户有透过Proxy时才会产生, 而且需要webserver的支持
     * @return string 客户端ip
     */
    public static function getClientIp()
    {
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ARR_HTTP_X_FORWARDED_FOR = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            return $ARR_HTTP_X_FORWARDED_FOR[0];
        }

        if (!empty($_SERVER['REMOTE_ADDR'])) {
            return $_SERVER['REMOTE_ADDR'];
        }

        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            return $_SERVER['HTTP_CLIENT_IP'];
        }

        return '';
    }
    
    /**
     * @return string 服务器ip
     */
    public static function getServerIp()
    {
        $SERVER_ADDR = !empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : false;
        return $SERVER_ADDR ? $SERVER_ADDR : '0';
    }
    
    /**
     * 上传了单个文件
     * @param $formName
     * @return array
     */
    public static function FileOne($formName)
    {
        if (empty($_FILES[$formName]['size'])) {
            return array();
        }
    
        //取得后缀
        $arrFileInfo = pathinfo($_FILES[$formName]['name']);
        return array(
            'name'      => $_FILES[$formName]['name'],
            'type'      => $_FILES[$formName]['type'],
            'size'      => $_FILES[$formName]['size'],
            'tmp_name'  => $_FILES[$formName]['tmp_name'],
            'error'     => $_FILES[$formName]['error'],
            'base_name' => $arrFileInfo['basename'],
            'extension' => $arrFileInfo['extension'],
        );
    }
    
    /**
     * 上传了多个文件
     * @param $formName
     * @return array
     */
    public static function FileMore($formName)
    {
        if (empty($_FILES[$formName])) {
            return array();
        }
    
        $arrImages = array();
        foreach ($_FILES[$formName]['name'] as $k => $name) {
            if (!empty($_FILES[$formName]['size'][$k])) {
                $arrFileInfo = pathinfo($name);
                $arrImages[$k] = array(
                    'name'      => $name,
                    'type'      => $_FILES[$formName]['type'][$k],
                    'size'      => $_FILES[$formName]['size'][$k],
                    'tmp_name'  => $_FILES[$formName]['tmp_name'][$k],
                    'error'     => $_FILES[$formName]['error'][$k],
                    'basename'  => $arrFileInfo['basename'],
                    'extension' => $arrFileInfo['extension'],
                );
            }
        }
    
        return $arrImages;
    }
    
    /**
     * 获取未修改过的提交信息
     * enctype="multipart/form-data" 的时候 php://input 是无效的
     * @return bool|string
     */
    public static function rawInput()
    {
        self::$data = file_get_contents('php://input', 'r');
        
        return self::$data;
    }

    /**
     * 一次性获取多个值
     * @param array $arr 需要的值, [字段名 => 默认值]
     * @param string $method
     */
    public static function pickData($arr, $method='post')
    {
        switch ($method) {
            case 'post':
                $data = Fun::pickArray($_POST, $arr);
                break;
            case 'get':
                $data = Fun::pickArray($_GET, $arr);
                break;
            case 'cookie':
                $data = Fun::pickArray($_COOKIE, $arr);
                break;
            case 'server':
                $data = Fun::pickArray($_SERVER, $arr);
                break;
            case 'request':
                $data = Fun::pickArray($_REQUEST, $arr);
                break;
            case 'session':
                $data = Fun::pickArray($_SESSION, $arr);
                break;
            case 'route':
                $data = Fun::pickArray(Route::$args, $arr);
                break;
            default:
                $data = [];
                break;
        }

        foreach ($data as $k => $v) {
            self::valid($k, $v);
        }

        return $data;
    }
    
}

//http://www.summer.com/index/index/req/a/4route/b?a=1get

//echo '<pre>';
//var_dump(Request::Get('a'));
//var_dump(Request::Get('b'));
//var_dump(Request::Post('a'));
//var_dump(Request::Cookie('a'));
//var_dump(Request::Route('a'));
//var_dump(Request::pickData(['a' => 0, 'b' => '', 'c' => '0'], 'get'));

//string(4) "1get"
//bool(false)
//bool(false)
//bool(false)
//string(6) "4route"
//array(3) {
//    ["a"]=>
//  string(1) "1"
//    ["b"]=>
//  string(0) ""
//    ["c"]=>
//  string(1) "0"
//}